#include "sm_nvs.h"
#include "nvs_flash.h"


void sm_nvs_flash_init(void)
{
    esp_err_t ret = nvs_flash_init();
	if (ret == ESP_ERR_NVS_NO_FREE_PAGES)
	{
		ESP_ERROR_CHECK(nvs_flash_erase());
		ret = nvs_flash_init();
	}
	ESP_ERROR_CHECK(ret);
}

esp_err_t sm_nvs_flash_write(const char* nvs_flash_name,const char* key,const char* value)
{
    esp_err_t err = 0;

    nvs_handle_t nvs_handle;

    err = nvs_open(nvs_flash_name,NVS_READWRITE,&nvs_handle);

	err |= nvs_set_str(nvs_handle,key,value);

	err |= nvs_commit(nvs_handle);

    nvs_close(nvs_handle);

    return err;
}

esp_err_t sm_nvs_flash_read(const char* nvs_flash_name,const char* key,char* value,size_t len)
{
    esp_err_t err = 0;

    nvs_handle_t nvs_handle;
    size_t _len = len;

    err = nvs_open(nvs_flash_name,NVS_READONLY,&nvs_handle);

    err |= nvs_get_str(nvs_handle,key,value,&_len);

    nvs_close(nvs_handle);
    
    return err;
}


esp_err_t sm_nvs_flash_erase_key(const char* nvs_flash_name,const char* key)
{
    esp_err_t err = 0;

    nvs_handle_t nvs_handle;

    err = nvs_open(nvs_flash_name,NVS_READWRITE,&nvs_handle);

    err |= nvs_erase_key(nvs_handle,key);

    err |= nvs_commit(nvs_handle);

    nvs_close(nvs_handle);

    return err;
}


